package com.timeset.activity.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.qiniu.common.QiniuException;
import com.timeset.activity.entity.*;
import com.timeset.activity.service.ActivityServiceImpl;
import com.timeset.photo.service.PhotoServiceImpl;
import com.timeset.user.controller.UserController;
import com.timeset.util.MultipartFileToFileUtil;
import com.timeset.util.QiniuUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName PhotoController
 * @Description
 * @Author lz
 * @Date 2020-04-23 18:06
 */
@RestController
@RequestMapping("/activities")
public class ActivityController {
    private List<Activities> list=new ArrayList<>();
    @Resource
    private ActivityServiceImpl activityService;
    @Resource
    private QiniuUtil qiniuUtil;
    @Resource
    private PhotoServiceImpl photoService;
    @RequestMapping("/whetherToApply")
    public String whetherToApply(@RequestParam("aId") int aId){
        ActivityApplyData applyData=activityService.activityApplyData(aId);
        Gson gson=new Gson();
        if(applyData==null) {
            return "";
        }else {
            return gson.toJson(applyData);
        }
    }
    //占位
    //开始申请，申请确认之前
    @RequestMapping("/startApply")
    public int startApply(@RequestParam("aId") int aId){
        ActivityApplyData applyData=activityService.activityApplyData(aId);
        int as=activityService.setApplyData(aId,applyData.getApplyingNum(),applyData.getFreeNum());
        return as;
    }
    //取消占位
    //开始申请，申请确认之前
    @RequestMapping("/CancelApply")
    public int CancelApply(@RequestParam("aId") int aId){
        ActivityApplyData applyData=activityService.activityApplyData(aId);
        int as=activityService.setCancelApplyData(aId,applyData.getApplyingNum(),applyData.getFreeNum());
        return as;
    }
    //准备申请参加toApplyToJoin：弹出框点击确认申请时
    @RequestMapping("/toApplyToJoin")
    public int toApplyToJoin(@RequestParam("userId")int userId,@RequestParam("aId") int aId){
        //查找数据库申请表是否存在该用户信息

        int result0= activityService.toApplyToJoin(aId,userId,3);
        return result0;

    }
    //申请参加：在申请页面点击申请时
    @RequestMapping("/applyToJoin")
    public int applyToJoin(@RequestParam("userId")int userId,@RequestParam("aId") int aId,@RequestParam("answer")String answer){
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmm");//设置日期格式
        String currentTime = df.format(new Date());//当前时间
        int result0= activityService.applyToJoin(aId,userId,answer,currentTime);
        int re=0;
        if(result0==1){//提交成功
            //修改人数
            ActivityApplyData applyData=activityService.activityApplyData(aId);
            int i=activityService.setApply(aId,applyData.getApplyingNum(),applyData.getJoinNum());
            while (i!=1){
                i=activityService.setApply(aId,applyData.getApplyingNum(),applyData.getJoinNum());
            }
            if(i==1){
                re=1;
            }
        }
         return re;
    }
    //取消申请：进入申请页面，点击返回或者超时造成页面关闭等finish操作，取消占位的同时删除apply表中的数据
    //取消申请参加活动
    @RequestMapping("/cancelApplyToJoin")
    public int cancelApplyToJoin(@RequestParam("aId")int aId,@RequestParam("userId")int userId){
        int i=1;
        if(activityService.isHaveApply(aId,userId)==1){
            i=activityService.cancelApplyToJoin(aId, userId);
        }
        return i;
    }

    //获取活动问题表
    @RequestMapping("/findQuestionByActivityId")
    public String getActivityApplyQuestion(@RequestParam("aId")int aId){
        String qustionList="";
        qustionList=activityService.findQuestionByActivityId(aId);
        return qustionList;

    }

    /*用户申请结果0是未申请 4申请失败，1是提交申请，2是申请成功：3正在提交申请*/
    @RequestMapping("/findAll")
    public List<Activities> findAll(@RequestParam("num")int num,@RequestParam("userId")int userId,@RequestParam("schoolId") int schoolId){
        System.out.println("查找所有活动"+num+userId);
        list=activityService.findAllActivities(num,schoolId);
        //对每一个activity的申请做判断
        for(Activities activities:list){

            if(activities.getIsSetJoinNum()!=0){

                //查询是否递交过该活动申请，并将申请状态发过去
                if(activityService.isHaveApply(activities.getId(),userId)==1){
                    int i=activityService.applyStatus(activities.getId(),userId);
                    System.out.println(i+"");
                    activities.setUserApplyStatus(i);
                }else {
                    activities.setUserApplyStatus(0);
                }
            }
        }


        System.out.println(list.toString());
        return list;
    }
    //上传活动
    @RequestMapping("/addNews")
    public int upActivity(@RequestParam("userId")int userId,@RequestParam("title") String title,@RequestParam("questionList") String qlist,
                          @RequestParam("context") String content,@RequestParam("tab") String la ,@RequestParam("peopleNum") int num,
                          @RequestParam("upTime") String up_time,@RequestParam("file") MultipartFile files[],HttpServletRequest request){
        Gson gson=new Gson();
        List<String> questionList=gson.fromJson(qlist,List.class);
        for(String s:questionList){
            System.out.println(s);
        }
        System.out.println(qlist);

        int result=0;//0是上传不成功，1是只有文字，2，文字图片都成功
        int okNum=0;//图片上传成功数量
        int isSetJoinNum=0;//是否设置了参加人数
        int isSetQuestions=0;//是否设置了问题表单

        if(num==0){
            isSetJoinNum=0;
        }else {
            isSetJoinNum=1;
            if(!qlist.equals("")){
                isSetQuestions=1;
            }else {
                isSetQuestions=0;
            }

        }
        String label=la.substring(2,la.length()-2);
        //上传文字
        Activities activities=new Activities(userId,up_time,1,content,label,title,isSetJoinNum);

        int i=activityService.addActivities(activities);
        int activityId=activities.getId();
        int re=0,joinOk=0;
        System.out.println("上传结果id："+i+activities.getId());
        if(i==1) {//插入数据成功

            if(num>0){//判断是否设置人数
                 joinOk=activityService.joinNum(activityId,num,num);
                 if(joinOk==1){//判断是否成功设置人数
                     re=1;
                     if(questionList.size()>0){//设置人数后是否设置问题表单
                         isSetQuestions=activityService.upQuestionList(activityId,qlist);
                         if(isSetQuestions==1){
                           re=1;
                         }else { re=0;
                         }
                     }

                 }

            }

            if((re==0&&num==0) ||(num!=0&&re==1) ){//成功的标记
                result=1;
            }else {//添加人数失败
                result=0;
                //删除活动
                activityService.deleteActivity(activityId);
            }
            //获取活动的id值
            if(files.length>0 && result==1) {
                MultipartFile fs[] = files;
                for (int j = 0; j < files.length; j++) {
                    MultipartFile file = fs[j];
                    System.out.println(file.getOriginalFilename());
                    String fileName = file.getOriginalFilename();
                    File f2 = null;
                    String path = "";
                    if (file != null) {
                        try {
                            f2 = MultipartFileToFileUtil.multipartFileToFile(file);
                            path = qiniuUtil.saveImage(f2, fileName);
                            System.out.println("path1" + path);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (path != null) {
                        int i1 = photoService.addImg(activityId, path);
                        if (i1 == 1) {
                            okNum=okNum+1;
                        }
                    }
                    MultipartFileToFileUtil.delteTempFile(f2);
                }
                if (okNum == fs.length) {
                    result = 2;//全部上传成功
                } else {
                   //删除上传成功的

                    List<Img> imgList=photoService.findImgIdByActivityId(activityId);
                    for (int i3=0;i3<imgList.size();i3++){
                        try {
                            qiniuUtil.delete(imgList.get(i3).getPath());
                        } catch (QiniuException e) {
                            e.printStackTrace();
                        }
                        photoService.deleteImg(imgList.get(i3).getImgId());

                    }
                    if(num>0){//如果还有设置参加人数，一并删除
                        activityService.deleteJoinNum(activityId);
                    }
                    activityService.deleteActivity(activityId);
                    result=0;
                }
            }
        }else {
            result=0;
        }
        return result;
    }






    @RequestMapping("/findActivitiesByOrganizationId")
    public List<Activities> findActivitiesByOrganizationId(@RequestParam("id") int id){
        System.out.println("根据组织id查找所有活动");
        list=activityService.findActivitiesByOrganizationId(id);
        return list;

    }
    @RequestMapping("/findActivitiesByLabel")
    public List<Activities> findActivitiesByLabel(@RequestParam("keyword") String tab){
        System.out.println("根据label查找所有活动");
        list=activityService.findActivitiesByLabel(tab);
        return list;
    }
    @RequestMapping("/findActivitiesByLevel")
    public List<Activities> findActivitiesByLevel(@RequestParam("level") String level){
        System.out.println("根据组织级别level查找所有活动");
        list=activityService.findActivitiesByLevel(level);
        return list;
    }
    /*
     * 历史活动
     *
     * */
    //根据组织id查找活动信息，根据每一个活动id查找活动申请信息
    @RequestMapping("/findHistoryActivityByOrgId")
    public List<Activity> findHistoryActivityByOrgId(@RequestParam("oId") int oId){
        List<Activity> activities1=new ArrayList<>();
        activities1=activityService.findHistoryActivityByOrgId(oId);
        for(int i=0;i<activities1.size();i++){
            if(activities1.get(i).getIsSetJoinNum()==1){
                ActivityApplyData applyData=activityService.activityApplyData(activities1.get(i).getId());
                activities1.get(i).setActivityApplyData(applyData);
            }
        }

        return activities1;
    }
    //结束活动
    @RequestMapping("/endActivityById")

    public int endActivityById(@RequestParam("aId") int aId){
        int result=activityService.endActivityById(aId);
        if(result==0){
            OnlyActivity activity=activityService.findActivityById(aId);
            if(activity!=null && activity.getStatus()==0){
                result=1;
            }
        }
        return result;
    }
    //删除活动deleteActivityById
    @RequestMapping("/deleteActivityById")
    public int deleteActivityById(@RequestParam("aId") int aId){
        int result=activityService.deleteActivityById(aId);
        if(result==0){//如果删除失败，查看是否是因为数据库没有该项数据
            OnlyActivity activity=activityService.findActivityById(aId);
            if(activity==null){
                result=1;
            }
        }
        return result;
    }
    //查找申请人员信息
    @RequestMapping("/findApplyInformationByAId")
    public List<ApplyForm> findApplyInformationByAId(@RequestParam("aId") int aId){
        return activityService.findApplyInformationByAId(aId);
    }
    //修改活动状态
    @RequestMapping("/updateApplyStatus")
    public int updateApplyStatus(@RequestParam("applyId") int applyId,@RequestParam("status") int status){
        int result=1;
        result=activityService.updateApplyStatus(applyId, status);
        if(result==0){//如果更改是失败的，查询是否还有该申请数据
            if(activityService.isHaveApplyById(applyId)==0){
                result=2;//数据库没有该条数据
            }else {
                int i=activityService.findApplyStatusById(applyId);
                if(i==2 || i==4){
                    result=1;//已经被修改过
                }else {//再次申请
                    result=activityService.updateApplyStatus(applyId, status);
                }
            }
        }
        return result;

    }
    //一键修改活动状态
    @RequestMapping("/updateApplyListStatus")
    public List<SetUpResult> updateApplyListStatus(@RequestParam("applyList") String str){
        Gson gson=new Gson();
        List<Integer> integerList=gson.fromJson(str,new TypeToken<List<Integer>>(){}.getType());
        List<SetUpResult> setUpResultList=new ArrayList<>();
        System.out.println(integerList.toString());
        int result=1;
        for(int j=0;j<integerList.size();j++){
            SetUpResult setUpResult=new SetUpResult();
            int applyId=integerList.get(j);
            setUpResult.setApplyId(applyId);
            result=activityService.updateApplyStatus(applyId, 2);
            if(result==0){//如果更改是失败的，查询是否还有该申请数据
                if(activityService.isHaveApplyById(applyId)==0){
                    result=2;//数据库没有该条数据
                }else {
                    int i=activityService.findApplyStatusById(applyId);
                    if(i==2 || i==4){
                        result=1;//已经被修改过
                    }else {//再次申请
                        result=activityService.updateApplyStatus(applyId, 2);
                    }
                }
            }
            setUpResult.setSetUpResult(result);
            setUpResultList.add(setUpResult);
        }
        System.out.println(setUpResultList.toString());
        return setUpResultList;
    }
}
